package main

import (
	"fmt"
	"html/template"
	"net/http"
)

func index(w http.ResponseWriter, r *http.Request) {
	//1.定义模板
	//2.解析模板
	t, err1 := template.ParseFiles("./index.tmpl")
	if err1 != nil {
		fmt.Printf("parse templates failed,err1:%v \n", err1)
		return
	}
	msg := "这是index页面"
	//3.渲染模板
	t.Execute(w, msg)
}

func home(w http.ResponseWriter, r *http.Request) {
	//1.定义模板
	//2.解析模板
	t, err2 := template.ParseFiles("./home.tmpl")
	if err2 != nil {
		fmt.Printf("parse templates failed,err2:%v \n", err2)
		return
	}
	msg := "这是home页面"
	//3.渲染模板
	t.Execute(w, msg)
}

func index2(w http.ResponseWriter, r *http.Request){
	//1.定义模板(模板继承的方式)
	//2.解析模板
	t,err3:=template.ParseFiles("./templates/base.tmpl","./templates/index.tmpl")
	if err3 != nil {
		fmt.Printf("parse templates failed,err3:%v \n", err3)
		return
	}
	msg := "小王子"
	//3.渲染模板
	t.ExecuteTemplate(w,"index.tmpl",msg)
}
func home2(w http.ResponseWriter, r *http.Request){
	//1.定义模板(模板继承的方式)
	//2.解析模板
	t,err4:=template.ParseFiles("./templates/base.tmpl","./templates/home.tmpl")
	if err4 != nil {
		fmt.Printf("parse templates failed,err4:%v \n", err4)
		return
	}
	msg := "小王子"
	//3.渲染模板
	t.ExecuteTemplate(w,"home.tmpl",msg)
}


func main() {
	http.HandleFunc("/index", index)
	http.HandleFunc("/home", home)
	http.HandleFunc("/index2", index2)
	http.HandleFunc("/home2", home2)
	err := http.ListenAndServe(":9090", nil)
	if err != nil {
		fmt.Printf("HTTP server start failed.err:%v \n", err)
		return
	}
}
